import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import React, { useMemo, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { DescriptionsType } from '@/components/DescriptionsType';
import { getUpdateConfig } from '../mconfig/UpdateConfig';
import { connect, history } from 'umi';
import { Button, Col, Form, Modal, Row, Space, Spin, Tabs, message } from 'antd';
import { warnManageService } from '../services';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { getUserDataList } from '@/services/BaseLayout';
import { EditOutlined } from '@ant-design/icons';
import { wareaddService, wareditService } from '../services/ManageServices';

const MyContext = React.createContext({});

const UpdataMaterialModal: React.FC<any> = ({ curRes, locationProps }) => {
  const { data, loading, pagination, searchList, getWarnData, reloadRefresh } = warnManageService(curRes);
  /** 样式根目录 */
  const styleFixCls = 'contract-styfixcls-';

  const [acceptForm] = Form.useForm();

  const { confirm } = Modal;

  /** 获取当前部门用户数据 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  /** 获取当前部门用户数据 */
  const changeGetUser = (value: string | number) => {
    acceptForm?.setFieldValue('storeDepartmentID', '');
    getUserRun({
      //获取当前使用部门用户信息
      userCompanyID: value,
    });
  };

  const wareaddCallback = (res) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      history.push({
        pathname: locationProps?.state?.returnPathName,
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    } else {
      message.error(res?.msg);
    }
  };

  const { wareaddRun } = wareaddService(wareaddCallback);

  const wareditCallback = (res) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      history.push({
        pathname: locationProps?.state?.returnPathName,
        state: {
          delRouterNameSource: history.location.pathname,
        },
      });
    } else {
      message.error(res?.msg);
    }
  };

  const { wareeditRun } = wareditService(wareditCallback);

  /** 获取表单配置
   *  @leftSelectName    左侧仓库名称
   *  @record   当前项
   */
  const { config, methods } = getUpdateConfig({
    acceptForm,
    pageType: locationProps.state.pageType,
    datalist: locationProps.state.data,
    storeList: data?.obj,
    getUserLoading,
    getUserList,
    changeGetUser,
  });

  // 暂存按钮
  const handleSave = () => {
    // 对表单进行校验，获取表单数据
    acceptForm.validateFields()?.then((values: any) => {
      // 组装数据
      let params = {
        ...values,
      };

      // 新增和修改接口
      if (locationProps?.state?.pageType == 'add') {
        wareaddRun(params);
      } else {
        params.id = locationProps?.state?.data?.id; // 修改 id
        wareeditRun(params);
      }
    });
  };

  const handleClose = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationProps?.state?.returnPathName,
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  /** 返回tab子页面 */
  const tabsItem = () => {
    let items: any[] = [
      {
        label: '仓库信息',
        key: '001',
        children: (
          <div className="commonTabsBodyDom">
            <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
              <ScrollBarLayout style={{ padding: '5px 20px' }}>
                <DescriptionsType config={config} />
              </ScrollBarLayout>
            </div>
            {/* <UpdateContractBottom {...obj} /> */}
            <div className="tabsBodyBottomBtn">
              <Space>
                <Button type={'primary'} icon={<EditOutlined />} onClick={handleSave}>
                  {/* {locationProps.state.pageType == 'add' ? '' : '编辑'} */}
                  保存
                </Button>
                <Button danger onClick={handleClose}>
                  关闭
                </Button>
              </Space>
            </div>
          </div>
        ),
      },
    ];
    return items;
  };

  // useEffect(()=>{
  //   console.log('123',storageRouterObj)
  // },[])

  return (
    <div className={'apply-update-UpdataIntentBox'}>
      <Spin spinning={false}>
        <Row gutter={[8, 8]} className={`${styleFixCls}row`}>
          <Col span={24} className={`${styleFixCls}row-col`}>
            <Tabs className={pageStyles['commonTabs']} type="card" onChange={(activeKey: string) => {}} items={tabsItem()} destroyInactiveTabPane={true} />
          </Col>
        </Row>
      </Spin>
    </div>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(UpdataMaterialModal);
